package com.web.exiaodao.business.controller;

import com.web.exiaodao.business.service.WalletTradeRecordService;
import com.web.exiaodao.remote.vo.WalletTradeRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author eason.zt
 * @version V1.0
 * @Title: WalletTradeRecordController.java
 * @Package com.web.webstart.business.controller
 * @Description: 钱包-交易记录,交易明细控制器
 * @date 2017-01-22 18:34:39
 */
@Controller
@RequestMapping("/cms/walletTradeRecord")
public class WalletTradeRecordController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(WalletTradeRecordController.class);

    @Autowired
    private WalletTradeRecordService walletTradeRecordService;

    /**
     * @param pageSize
     * @param status     //默认查询非删除3的数据,具体类型参照XaConstant.Status
     *                   //@param sortData
     * @param jsonFilter
     * @return
     * @Title: findWalletTradeRecordNEStatusPage
     * @Description: 分页查询WalletTradeRecord     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findWalletTradeRecordNEStatusPage", method = RequestMethod.POST)
    public XaResult<Page<WalletTradeRecordVo>> findWalletTradeRecordNEStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "3") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<WalletTradeRecordVo>> xr = new XaResult<>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
        xr = walletTradeRecordService.findListNEStatusByFilter(status, filterParams, pageable);
        return xr;
    }

    /**
     * @param pageSize
     * @param status     //默认查询正常状态1的数据,具体类型参照XaConstant.Status
     *                   //@param sortData
     * @param jsonFilter
     * @return
     * @Title: findWalletTradeRecordEQStatusPage
     * @Description: (预留)分页查询WalletTradeRecord     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findWalletTradeRecordEQStatusPage", method = RequestMethod.POST)
    public XaResult<Page<WalletTradeRecordVo>> findWalletTradeRecordEQStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<WalletTradeRecordVo>> xr = new XaResult<>();
        try {
            Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
            Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
            xr = walletTradeRecordService.findListEQStatusByFilter(status, filterParams, pageable);
        } catch (Exception e) {
            xr.error(e instanceof BusinessException ? e.getMessage() : XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error + e.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @param modelId
     * @return
     * @Title: findWalletTradeRecordById
     * @Description: 根据ID查找单条实体
     */
    @ResponseBody
    @RequestMapping(value = "findWalletTradeRecordById", method = RequestMethod.POST)
    public XaResult<WalletTradeRecordVo> findWalletTradeRecordById(
            @RequestParam Long modelId
    ) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        try {
            xr = walletTradeRecordService.findOne(modelId);
        } catch (Exception e) {
            xr.error(e instanceof BusinessException ? e.getMessage() : XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error + e.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @param model
     * @return
     * @Title: saveModel
     * @Description: 保存实体数据
     */
    @ResponseBody
    @RequestMapping(value = "saveWalletTradeRecord", method = RequestMethod.POST)
    public XaResult<WalletTradeRecordVo> saveWalletTradeRecord(
            HttpServletRequest request,
            WalletTradeRecordVo model
    ) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        try {
            model.setCreateUser(request.getSession().getAttribute(XaConstant.SessionKey.currentUser).toString());
            xr = walletTradeRecordService.saveOrUpdate(model);
        } catch (Exception e) {
            xr.error(e instanceof BusinessException ? e.getMessage() : XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error + e.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @param modelIds 多个实体id,中间用逗号隔开
     * @param status   操作类型,status类型见XaConstant.Status,默认删除操作
     * @return
     * @Title: multiOperateWalletTradeRecordByIds
     * @Description: 批量操作多个实体状态, 根据status进行操作
     */
    @ResponseBody
    @RequestMapping(value = "operateWalletTradeRecordByIds", method = RequestMethod.POST)
    public XaResult<WalletTradeRecordVo> operateWalletTradeRecordByIds(
            HttpServletRequest request,
            @RequestParam String modelIds,
            @RequestParam(defaultValue = "3") Integer status
    ) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        try {
            xr = walletTradeRecordService.multiOperate(modelIds, status);
        } catch (Exception e) {
            xr.error(e instanceof BusinessException ? e.getMessage() : XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error + e.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @param photoFile
     * @param request
     * @return
     * @Title: upload
     * @Description: 图片上传
     */
    @ResponseBody
    @RequestMapping(value = "photoUpload", method = RequestMethod.POST)
    public XaResult<String> photoUpload(
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
            HttpServletRequest request) {
        XaResult<String> xr = new XaResult<String>();
        if (photoFile == null) {
            xr.error("请先选择上传的图片或者文件！");
            return xr;
        }
        if (photoFile.getSize() > XaConstant.FileMgr.IMG_MaxValue) {
            xr.error(XaConstant.FileMgr.IMG_ERROR);
            return xr;
        }
        String root = request.getSession().getServletContext().getRealPath("/");
        String picturePath = "/upload/walletTradeRecord";
        String ext = photoFile.getOriginalFilename().substring(
                photoFile.getOriginalFilename().lastIndexOf("."));
        String newName = new Date().getTime() + ext;
        File filedict = new File(root + picturePath);
        if (!filedict.exists()) {
            filedict.mkdir();
        }
        File targetFile = new File(root + picturePath + File.separator
                + newName);
        try {
            if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpg")
                    || org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".png")) {
                //把photoFile的io数据写入到targetFile
                photoFile.transferTo(targetFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                //Map<String, Integer> map = new HashMap<String, Integer>();
                //map.put("pictureHeight", height);
                //map.put("pictureWidth", width);
                xr.setCode(1);
                xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
                        + newName + ":" + height + ":" + width);
            } else {
                xr.setCode(0);
                xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传jpg/png图片");
            }
        } catch (IllegalStateException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
        } catch (IOException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
        } catch (Exception e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
        }
        return xr;
    }

}

